<template>
  <div class="allBody">
    <common-header title="选择地址"></common-header>
    <div class="headerWrap">
      <van-address-list
        v-model="chosenAddressId"
        :list="list"
        default-tag-text="默认"
        @add="onAdd"
        @edit="onEdit"
        @select="onSelect"
        v-if="list.length"
      />
      <div class="noAddress" v-if="!list.length" @click="$router.push('/contactAdd')">
        <van-icon class="iconfont" class-prefix="icon" name="jiahao" size="30"></van-icon>
        <span>添加新地址</span>
      </div>
    </div>
  </div>
</template>

<script>
import CommonHeader from '@components/CommonHeader'
import { mapMutations, mapState } from 'vuex'
import { Toast } from 'vant'
export default {
  computed: {
    ...mapState({
      list: state => state.contact.contacts
    })
  },
  data () {
    return {
      chosenAddressId: 1
    }
  },
  created () {
    this.showDefault()
  },
  methods: {
    // 默认的地址前面打上钩子
    showDefault () {
      // 查询地址列表中是否有默认的地址
      if (this.list.length) {
        const defaultItem = this.list.find(ele => ele.isDefault)
        if (defaultItem) {
          this.chosenAddressId = defaultItem.id
        } else {
          // 如果没有默认是列表地址的第一个地址
          this.chosenAddressId = this.list[0].id
        }
      }
    },
    onAdd () {
      this.$router.push('/contactAdd')
    },
    onEdit (item, index) {
      this.$router.push({
        path: '/contactEdit',
        query: {
          index
        }
      })
    },
    // 选择更新订单联系人
    onSelect (item, index) {
      Toast({
        message: '更换成功',
        duration: 500,
        onClose: () => {
          this.setOrderContact(item)
          this.$router.push('/order')
        }
      })
    },
    ...mapMutations('order', ['setOrderContact'])
  },
  components: {
    CommonHeader
  }
}
</script>

<style lang="scss" scoped>
.noAddress {
  font-size: 22PX;
  border-bottom: 2px solid #000;
  padding: 10px 0;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
